package com.web.nyist.controller.api;

import com.web.nyist.common.JsonReturnCode;
import com.web.nyist.dto.JSONError;
import com.web.nyist.dto.JSONResponse;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;


public class JSONController {
    protected static final Logger logger = Logger.getLogger(JSONController.class);

    /**
     * 用于处理异常的
     *
     * @return
     */
    @ExceptionHandler({Exception.class})
    public
    @ResponseBody
    JSONResponse exception(Exception e) {
        logger.error(e.getMessage(), e);
        JSONResponse ret = new JSONResponse();
        ret.setCode(JsonReturnCode.服务器错误.value);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        ret.setMessage(sw.toString());
        ret.setErrors(new ArrayList<JSONError>());
        return ret;
    }

    protected JSONResponse succeed(Object obj) {
        JSONResponse ret = new JSONResponse();
        ret.setCode(JsonReturnCode.正常.value);
        ret.setReturnObject(obj);
        ret.setErrors(new ArrayList<JSONError>());
        return ret;
    }


    protected JSONResponse failed(ArrayList<JSONError> errors) {
        JSONResponse ret = new JSONResponse();
        ret.setCode(JsonReturnCode.业务逻辑错误.value);
        ret.setErrors(errors);
        return ret;
    }
}
